/************************************************************************
  Copyright (c) IPADS@SJTU 2021. All rights reserved.

  This file test GM/T SM2 implementation, check whether it can be verified with OpenSSL.
**************************************************************************/

#include "SM2_sv.h"

#include "eapp.h"
#include "print.h"

#define HASH_SIZE 32

void printHex(unsigned char *c, int n)
{
	int i, rounds;
    rounds = n / 16;
	for (i = 0; i < rounds; i++) {
		eapp_print("%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d\n",
                    c[i*16], c[i*16+1], c[i*16+2], c[i*16+3],
                    c[i*16+4], c[i*16+5], c[i*16+6], c[i*16+7],
                    c[i*16+8], c[i*16+9], c[i*16+10], c[i*16+11],
                    c[i*16+12], c[i*16+13], c[i*16+14], c[i*16+15]);
	}
}

int test(unsigned long * args)
{
    int ret = SM2_SelfCheck();
    eapp_print("result = %d\n", ret);
    if(ret) {
        eapp_print("fail selfcheck\n");
    }

    //the private key
	unsigned char dA[32] = {
			0x15, 0xea, 0x97, 0x3a, 0xd0, 0x4e, 0xcb, 0x28, 0x04, 0x06, 0xe2, 0x0a, 0x32, 0xf0, 0xcf, 0x51,
            0xf9, 0x21, 0x5a, 0x0f, 0x36, 0x60, 0x9a, 0x2b, 0x81, 0x2a, 0xcb, 0x7b, 0xb8, 0x89, 0x3d, 0xb1};
    
    /**** check pub key ****/
    //the public key
	unsigned char xA[32], yA[32];
	int temp;

    temp = SM2_make_pubkey(dA, xA, yA);
	if (temp)
		return temp;
    eapp_print("pubkey xA:\n");
    printHex(xA, 32);
    eapp_print("\nyA:\n");
    printHex(yA, 32);
    eapp_print("\nCheck pub end\n");

	// message
    unsigned char message[HASH_SIZE] = {
            0x44, 0xcc, 0xcb, 0xdf, 0x1d, 0xfb, 0x04, 0x00, 0xf9, 0x0f, 0x38, 0xc6, 0x55, 0x7d, 0x15, 0xf5,
            0xcf, 0x2c, 0xd8, 0xd9, 0xc6, 0x6c, 0x81, 0x7b, 0xc3, 0x4a, 0x5b, 0x9e, 0xe3, 0xfd, 0xe1, 0xea};

    int len = HASH_SIZE;
	eapp_print("hash_len: %d\n", len);
	printHex(message, HASH_SIZE);

    // Signature generated by OpenSSL
    unsigned char r[32] = {
			0x14, 0x71, 0xB4, 0x0F, 0xB7, 0x71, 0xF7, 0xDF, 0xDA, 0xD4, 0x53, 0x1C, 0x53, 0xDE, 0xB5, 0xC3,
			0xAB, 0x1E, 0x6E, 0xF5, 0xE1, 0x0B, 0x89, 0x6E, 0xEB, 0x5F, 0x52, 0x7C, 0x92, 0x4F, 0xB8, 0x6C};
    unsigned char s[32] = {
            0x77, 0x7D, 0x5F, 0x91, 0x0E, 0xE3, 0xFA, 0x2A, 0xF4, 0x97, 0x81, 0x7A, 0xDB, 0xF5, 0x21, 0xA4,
			0xA6, 0x13, 0x8D, 0xF6, 0x58, 0x6E, 0x17, 0x53, 0x78, 0xC5, 0x09, 0x4E, 0xEC, 0xFB, 0x7E, 0x29};

    temp = SM2_Verify(message, len, xA, yA, r, s);
	if (temp){
        eapp_print("Verify signature Fail\n");
    } else {
        eapp_print("Verify successfully\n");
    }
    
    return 0;
}

int EAPP_ENTRY main(){
  unsigned long * args;
  EAPP_RESERVE_REG;
  unsigned long ret = test(args);
  EAPP_RETURN((unsigned long)ret);
}
